﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

public class AssetStatisticsController : Controller
{
    private AssetDBEntities1 db = new AssetDBEntities1();

    public ActionResult Index()
    {
        List<AssetStatisticsViewModel> results = new List<AssetStatisticsViewModel>();

        try
        {
            string connectionString = GetConnectionString();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // 先测试连接
                try
                {
                    connection.Open();
                }
                catch (SqlException sqlEx)
                {
                    ViewBag.Error = $"数据库连接失败: {sqlEx.Message}";
                    return View(results);
                }

                using (SqlCommand command = new SqlCommand("pro_N2512AssetInfo", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandTimeout = 30; // 设置超时时间

                    try
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                // 获取所有列名
                                var columns = new List<string>();
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    columns.Add(reader.GetName(i));
                                }

                                int rowCount = 0;
                                while (reader.Read())
                                {
                                    rowCount++;
                                    var assetStat = new AssetStatisticsViewModel();

                                    for (int i = 0; i < reader.FieldCount; i++)
                                    {
                                        string columnName = reader.GetName(i);
                                        object columnValue = reader[i];

                                        // 根据列名分配值
                                        if (columnName.Equals("AssetName", StringComparison.OrdinalIgnoreCase))
                                        {
                                            assetStat.AssetName = columnValue?.ToString() ?? "未知资产";
                                        }
                                        else if (columnName.Equals("sNum", StringComparison.OrdinalIgnoreCase))
                                        {
                                            assetStat.SNum = columnValue?.ToString() ?? "0";
                                        }
                                        else
                                        {
                                            // 区域列 - 动态列
                                            decimal? decimalValue = null;

                                            if (columnValue != DBNull.Value && columnValue != null)
                                            {
                                                try
                                                {
                                                    decimalValue = Convert.ToDecimal(columnValue);
                                                }
                                                catch
                                                {
                                                    // 如果转换失败，尝试解析字符串
                                                    if (decimal.TryParse(columnValue.ToString(), out decimal parsedValue))
                                                    {
                                                        decimalValue = parsedValue;
                                                    }
                                                }
                                            }

                                            assetStat.AreaValues[columnName] = decimalValue;
                                        }
                                    }

                                    results.Add(assetStat);
                                }

                                ViewBag.SuccessMessage = $"成功加载 {rowCount} 条资产记录";
                            }
                            else
                            {
                                ViewBag.Message = "存储过程未返回任何数据";
                            }
                        }
                    }
                    catch (SqlException ex)
                    {
                        ViewBag.Error = $"执行存储过程时出错: {ex.Message}";
                        // 记录详细错误信息
                        System.Diagnostics.Debug.WriteLine($"SQL错误: {ex.Message}, 错误号: {ex.Number}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ViewBag.Error = $"系统错误: {ex.Message}";
        }

        return View(results);
    }

    private string GetConnectionString()
    {
        try
        {
            string connectionString = db.Database.Connection.ConnectionString;

            if (connectionString.Contains("metadata=") && connectionString.Contains("provider connection string="))
            {
                int start = connectionString.IndexOf("provider connection string=\"") + "provider connection string=\"".Length;
                int end = connectionString.IndexOf("\"", start);
                if (start > 0 && end > start)
                {
                    return connectionString.Substring(start, end - start).Replace("\\\"", "\"");
                }
            }

            return connectionString;
        }
        catch
        {
            return ConfigurationManager.ConnectionStrings["AssetDBEntities1"]?.ConnectionString ??
                   "Data Source=.;Initial Catalog=AssetDB;Integrated Security=True";
        }
    }
}